﻿using System;
using System.Threading;
using MxNetwork;
using GameTools;

namespace DTFight
{
	class MainClass
	{
		static void  CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Log.WriteLog(string.Format("应用程序出现异常，请重新启动！异常情况如下:\r\n{0}", e.ExceptionObject.ToString()));


			Environment.Exit(0); //0代表正常退出，非0代表某种错误的退出
		}

		public static void Main (string[] args)
		{
			// 防止自动弹出“XXXX程序已停止工作”的对话框
			AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

			Console.WriteLine ("Hello World!");

			init();
			update();
			destroy();

			Console.ReadKey ();
		}

		static void init()
		{
			ClientMgr.Instance ().Init ();
			RoomMsg.Instance ().Init ();
			GameMgr.Instance.Init ();

			NetworkDispatcher.Instance.CreateServer ("127.0.0.1", 50010);
			//NetworkDispatcher.Instance.CreateServer ("120.27.34.224", 50000);
		}

		static void destroy()
		{
			GameMgr.Instance.Destroy ();
			RoomMsg.Instance ().Destroy ();
			ClientMgr.Instance ().Init ();
		}

		static void update()
		{
			AutoResetEvent myEvent = new AutoResetEvent(false);
			while (true) {
				DateTime preTime = DateTime.Now;

				NetworkDispatcher.Instance.Update ();
				GameMgr.Instance.Update ();

				TimeSpan time = DateTime.Now - preTime;
				if (time.TotalMilliseconds < 20)
				{
					myEvent.WaitOne((int)(20 - time.TotalMilliseconds)); 
				}
			}
		}
	}
}
